home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / misc / volume6 / compress.cms < prev    next >
Encoding:
Text File  |  1989-04-08  |  43.7 KB  |  1,609 lines

  1. Newsgroups: comp.sources.misc
  2. From: allbery@uunet.UU.NET (Brandon S. Allbery - comp.sources.misc)
  3. Subject: v06i085: compress for IBM/VM CMS
  4. Reply-To: billr@saab.cna.tek.com (Bill Randle)
  5.  
  6. Posting-number: Volume 6, Issue 85
  7. Submitted-by: billr@saab.cna.tek.com (Bill Randle)
  8. Archive-name: compress.cms
  9.  
  10. This was sent to me by a games person who uses it to maintain his BITNET
  11. archive. I thought it might be worth further distribution.  Define CMS
  12. to get the CMS specific stuff.
  13.  
  14.         -Bill
  15.  
  16. #! /bin/sh
  17. # This is a shell archive.  Remove anything before this line, then unpack
  18. # it by saving it into a file and typing "sh file".  To overwrite existing
  19. # files, type "sh file -c".  You can also feed this as standard input via
  20. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  21. # will see the following message at the end:
  22. #        "End of shell archive."
  23. # Contents:  compress.c
  24. # Wrapped by billr@saab on Tue Apr  4 10:52:24 1989
  25. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  26. if test -f 'compress.c' -a "${1}" != "-c" ; then 
  27.   echo shar: Will not clobber existing file \"'compress.c'\"
  28. else
  29. echo shar: Extracting \"'compress.c'\" \(41795 characters\)
  30. sed "s/^X//" >'compress.c' <<'END_OF_FILE'
  31. X#ifndef lint
  32. Xstatic char sccsid[] = "@(#)compress.c    @(#)compress.c    5.9 (Berkeley) 5/11/86";
  33. X#endif not lint
  34. X
  35. X/* 
  36. X * Compress - data compression program 
  37. X */
  38. X#define    min(a,b)    ((a>b) ? b : a)
  39. X
  40. X/*
  41. X * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt, CMS
  42. X */
  43. X
  44. X/*
  45. X * Set USERMEM to the maximum amount of physical user memory available
  46. X * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  47. X * for compression.
  48. X *
  49. X * SACREDMEM is the amount of physical memory saved for others; compress
  50. X * will hog the rest.
  51. X */
  52. X#ifndef SACREDMEM
  53. X#define SACREDMEM    0
  54. X#endif
  55. X
  56. X#ifndef USERMEM
  57. X# define USERMEM     450000    /* default user memory */
  58. X#endif
  59. X
  60. X#ifdef interdata        /* (Perkin-Elmer) */
  61. X#define SIGNED_COMPARE_SLOW    /* signed compare is slower than unsigned */
  62. X#endif
  63. X
  64. X#ifdef pdp11
  65. X# define BITS     12    /* max bits/code for 16-bit machine */
  66. X# define NO_UCHAR    /* also if "unsigned char" functions as signed char */
  67. X# undef USERMEM 
  68. X#endif /* pdp11 */    /* don't forget to compile with -i */
  69. X
  70. X#ifdef z8000
  71. X# define BITS     12
  72. X# undef vax        /* weird preprocessor */
  73. X# undef USERMEM 
  74. X#endif /* z8000 */
  75. X
  76. X#ifdef pcxt
  77. X# define BITS   12
  78. X# undef USERMEM
  79. X#endif /* pcxt */
  80. X
  81. X#ifdef USERMEM
  82. X# if USERMEM >= (433484+SACREDMEM)
  83. X#  define PBITS    16
  84. X# else
  85. X#  if USERMEM >= (229600+SACREDMEM)
  86. X#   define PBITS    15
  87. X#  else
  88. X#   if USERMEM >= (127536+SACREDMEM)
  89. X#    define PBITS    14
  90. X#   else
  91. X#    if USERMEM >= (73464+SACREDMEM)
  92. X#     define PBITS    13
  93. X#    else
  94. X#     define PBITS    12
  95. X#    endif
  96. X#   endif
  97. X#  endif
  98. X# endif
  99. X# undef USERMEM
  100. X#endif /* USERMEM */
  101. X
  102. X#ifdef PBITS        /* Preferred BITS for this memory size */
  103. X# ifndef BITS
  104. X#  define BITS PBITS
  105. X# endif BITS
  106. X#endif /* PBITS */
  107. X
  108. X#if BITS == 16
  109. X# define HSIZE    69001        /* 95% occupancy */
  110. X#endif
  111. X#if BITS == 15
  112. X# define HSIZE    35023        /* 94% occupancy */
  113. X#endif
  114. X#if BITS == 14
  115. X# define HSIZE    18013        /* 91% occupancy */
  116. X#endif
  117. X#if BITS == 13
  118. X# define HSIZE    9001        /* 91% occupancy */
  119. X#endif
  120. X#if BITS <= 12
  121. X# define HSIZE    5003        /* 80% occupancy */
  122. X#endif
  123. X
  124. X#ifdef M_XENIX            /* Stupid compiler can't handle arrays with */
  125. X# if BITS == 16            /* more than 65535 bytes - so we fake it */
  126. X#  define XENIX_16
  127. X# else
  128. X#  if BITS > 13            /* Code only handles BITS = 12, 13, or 16 */
  129. X#   define BITS    13
  130. X#  endif
  131. X# endif
  132. X#endif
  133. X
  134. X/*
  135. X * a code_int must be able to hold 2**BITS values of type int, and also -1
  136. X */
  137. X#if BITS > 15
  138. Xtypedef long int    code_int;
  139. X#else
  140. Xtypedef int        code_int;
  141. X#endif
  142. X
  143. X#ifdef SIGNED_COMPARE_SLOW
  144. Xtypedef unsigned long int count_int;
  145. Xtypedef unsigned short int count_short;
  146. X#else
  147. Xtypedef long int      count_int;
  148. X#endif
  149. X
  150. X#ifdef NO_UCHAR
  151. X typedef char    char_type;
  152. X#else
  153. X typedef    unsigned char    char_type;
  154. X#endif /* UCHAR */
  155. X
  156. X#ifndef CMS
  157. Xchar_type magic_header[] = { "\037\235" };    /* 1F 9D */
  158. X#else
  159. Xchar_type magic_header[] = { 0x1f , 0x9d } ;      /* 1F 9D */
  160. X#endif /*CMS*/
  161. X
  162. X/* Defines for third byte of header */
  163. X#define BIT_MASK    0x1f
  164. X#define BLOCK_MASK    0x80
  165. X/* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  166. X   a fourth header byte (for expansion).
  167. X*/
  168. X#define INIT_BITS 9            /* initial number of bits/code */
  169. X
  170. X/*
  171. X * compress.c - File compression ala IEEE Computer, June 1984.
  172. X *
  173. X * Authors:    Spencer W. Thomas    (decvax!utah-cs!thomas)
  174. X *        Jim McKie        (decvax!mcvax!jim)
  175. X *        Steve Davies        (decvax!vax135!petsd!peora!srd)
  176. X *        Ken Turkowski        (decvax!decwrl!turtlevax!ken)
  177. X *        James A. Woods        (decvax!ihnp4!ames!jaw)
  178. X *        Joe Orost        (decvax!vax135!petsd!joe)
  179. X *
  180. X * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  181. X * $Log:    compress.c,v $
  182. X * Revision 4.0  85/07/30  12:50:00  joe
  183. X * Removed ferror() calls in output routine on every output except first.
  184. X * Prepared for release to the world.
  185. X * 
  186. X * Revision 3.6  85/07/04  01:22:21  joe
  187. X * Remove much wasted storage by overlaying hash table with the tables
  188. X * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  189. X * computations.  Fixed dump_tab() DEBUG routine.
  190. X *
  191. X * Revision 3.5  85/06/30  20:47:21  jaw
  192. X * Change hash function to use exclusive-or.  Rip out hash cache.  These
  193. X * speedups render the megamemory version defunct, for now.  Make decoder
  194. X * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  195. X *
  196. X * Revision 3.4  85/06/27  12:00:00  ken
  197. X * Get rid of all floating-point calculations by doing all compression ratio
  198. X * calculations in fixed point.
  199. X *
  200. X * Revision 3.3  85/06/24  21:53:24  joe
  201. X * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  202. X * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  203. X *
  204. X * Revision 3.2  85/06/06  21:53:24  jaw
  205. X * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  206. X * Default to "quiet" output (no compression statistics).
  207. X *
  208. X * Revision 3.1  85/05/12  18:56:13  jaw
  209. X * Integrate decompress() stack speedups (from early pointer mods by McKie).
  210. X * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  211. X * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase 
  212. X * output byte count by magic number size.
  213. X * 
  214. X * Revision 3.0   84/11/27  11:50:00  petsd!joe
  215. X * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  216. X * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  217. X * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  218. X *
  219. X * Revision 2.7   84/11/16  19:35:39  ames!jaw
  220. X * Cache common hash codes based on input statistics; this improves
  221. X * performance for low-density raster images.  Pass on #ifdef bundle
  222. X * from Turkowski.
  223. X *
  224. X * Revision 2.6   84/11/05  19:18:21  ames!jaw
  225. X * Vary size of hash tables to reduce time for small files.
  226. X * Tune PDP-11 hash function.
  227. X *
  228. X * Revision 2.5   84/10/30  20:15:14  ames!jaw
  229. X * Junk chaining; replace with the simpler (and, on the VAX, faster)
  230. X * double hashing, discussed within.  Make block compression standard.
  231. X *
  232. X * Revision 2.4   84/10/16  11:11:11  ames!jaw
  233. X * Introduce adaptive reset for block compression, to boost the rate
  234. X * another several percent.  (See mailing list notes.)
  235. X *
  236. X * Revision 2.3   84/09/22  22:00:00  petsd!joe
  237. X * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  238. X * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  239. X *
  240. X * Revision 2.2   84/09/18  14:12:21  ames!jaw
  241. X * Fold in news changes, small machine typedef from thomas,
  242. X * #ifdef interdata from joe.
  243. X *
  244. X * Revision 2.1   84/09/10  12:34:56  ames!jaw
  245. X * Configured fast table lookup for 32-bit machines.
  246. X * This cuts user time in half for b <= FBITS, and is useful for news batching
  247. X * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  248. X * added signal catcher [plus beef in writeerr()] to delete effluvia.
  249. X *
  250. X * Revision 2.0   84/08/28  22:00:00  petsd!joe
  251. X * Add check for foreground before prompting user.  Insert maxbits into
  252. X * compressed file.  Force file being uncompressed to end with ".Z".
  253. X * Added "-c" flag and "zcat".  Prepared for release.
  254. X *
  255. X * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  256. X * Will only compress regular files (no directories), added a magic number
  257. X * header (plus an undocumented -n flag to handle old files without headers),
  258. X * added -f flag to force overwriting of possibly existing destination file,
  259. X * otherwise the user is prompted for a response.  Will tack on a .Z to a
  260. X * filename if it doesn't have one when decompressing.  Will only replace
  261. X * file if it was compressed.
  262. X *
  263. X * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  264. X * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  265. X * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  266. X * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  267. X * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  268. X * 1.8.
  269. X *
  270. X * Revision 1.8  84/08/09  23:15:00  joe
  271. X * Made it compatible with vax version, installed jim's fixes/enhancements
  272. X *
  273. X * Revision 1.6  84/08/01  22:08:00  joe
  274. X * Sped up algorithm significantly by sorting the compress chain.
  275. X *
  276. X * Revision 1.5  84/07/13  13:11:00  srd
  277. X * Added C version of vax asm routines.  Changed structure to arrays to
  278. X * save much memory.  Do unsigned compares where possible (faster on
  279. X * Perkin-Elmer)
  280. X *
  281. X * Revision 1.4  84/07/05  03:11:11  thomas
  282. X * Clean up the code a little and lint it.  (Lint complains about all
  283. X * the regs used in the asm, but I'm not going to "fix" this.)
  284. X *
  285. X * Revision 1.3  84/07/05  02:06:54  thomas
  286. X * Minor fixes.
  287. X *
  288. X * Revision 1.2  84/07/05  00:27:27  thomas
  289. X * Add variable bit length output.
  290. X *
  291. X */
  292. Xstatic char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  293. X
  294. X#include <stdio.h>
  295. X#include <ctype.h>
  296. X#include <signal.h>
  297. X#ifndef CMS
  298. X#include <sys/types.h>
  299. X#include <sys/stat.h>
  300. X#else /*CMS*/
  301. X#include <types.h>
  302. X#include <stat.h>
  303. X#include <time.h>
  304. X#include <string.h>
  305. X#include <file.h>
  306. X#include <stdlib.h>
  307. X#endif /*CMS*/
  308. X#ifdef notdef
  309. X#include <sys/ioctl.h>
  310. X#endif
  311. X
  312. X#define ARGVAL() (*++(*argv) || (--argc && *++argv))
  313. X
  314. Xint n_bits;                /* number of bits/code */
  315. Xint maxbits = BITS;            /* user settable max # bits/code */
  316. Xcode_int maxcode;            /* maximum code, given n_bits */
  317. Xcode_int maxmaxcode = 1 << BITS;    /* should NEVER generate this code */
  318. X#ifdef COMPATIBLE        /* But wrong! */
  319. X# define MAXCODE(n_bits)    (1 << (n_bits) - 1)
  320. X#else
  321. X# define MAXCODE(n_bits)    ((1 << (n_bits)) - 1)
  322. X#endif /* COMPATIBLE */
  323. X
  324. X#ifdef XENIX_16
  325. Xcount_int htab0[8192];
  326. Xcount_int htab1[8192];
  327. Xcount_int htab2[8192];
  328. Xcount_int htab3[8192];
  329. Xcount_int htab4[8192];
  330. Xcount_int htab5[8192];
  331. Xcount_int htab6[8192];
  332. Xcount_int htab7[8192];
  333. Xcount_int htab8[HSIZE-65536];
  334. Xcount_int * htab[9] = {
  335. X    htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  336. X
  337. X#define htabof(i)    (htab[(i) >> 13][(i) & 0x1fff])
  338. Xunsigned short code0tab[16384];
  339. Xunsigned short code1tab[16384];
  340. Xunsigned short code2tab[16384];
  341. Xunsigned short code3tab[16384];
  342. Xunsigned short code4tab[16384];
  343. Xunsigned short * codetab[5] = {
  344. X    code0tab, code1tab, code2tab, code3tab, code4tab };
  345. X
  346. X#define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  347. X
  348. X#else /*XENIX_16*/    /* Normal machine */
  349. X
  350. X#ifndef CMS
  351. X#ifdef sel    /* gould base register braindamage */
  352. X/*NOBASE*/
  353. Xcount_int htab [HSIZE];
  354. Xunsigned short codetab [HSIZE];
  355. X/*NOBASE*/
  356. X#else
  357. Xcount_int htab [HSIZE];
  358. Xunsigned short codetab [HSIZE];
  359. X#endif sel
  360. X
  361. X#else /*CMS*/
  362. X/* use malloc() to allocate memory for the tables at run
  363. X   time - As the tables are defined here they appear
  364. X   FULLY IN THE EXECUTABLE FILE ON DISK (USING WATERLOO C 3.0)
  365. X   USING MALLOC AT RUN TIME SAVES A LOT OF DISKSPACE.     */
  366. Xcount_int *htab;
  367. Xunsigned short *codetab;
  368. X#endif /*CMS*/
  369. X
  370. X#define htabof(i)    htab[i]
  371. X#define codetabof(i)    codetab[i]
  372. X#endif    /* XENIX_16 */
  373. Xcode_int hsize = HSIZE;            /* for dynamic table sizing */
  374. Xcount_int fsize;
  375. X
  376. X/*
  377. X * To save much memory, we overlay the table used by compress() with those
  378. X * used by decompress().  The tab_prefix table is the same size and type
  379. X * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  380. X * get this from the beginning of htab.  The output stack uses the rest
  381. X * of htab, and contains characters.  There is plenty of room for any
  382. X * possible stack (stack used to be 8000 characters).
  383. X */
  384. X
  385. X#define tab_prefixof(i)    codetabof(i)
  386. X#ifdef XENIX_16
  387. X# define tab_suffixof(i)    ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  388. X# define de_stack        ((char_type *)(htab2))
  389. X#else    /* Normal machine */
  390. X# define tab_suffixof(i)    ((char_type *)(htab))[i]
  391. X# define de_stack        ((char_type *)&tab_suffixof(1<<BITS))
  392. X#endif    /* XENIX_16 */
  393. X
  394. Xcode_int free_ent = 0;            /* first unused entry */
  395. Xint exit_stat = 0;            /* per-file status */
  396. Xint perm_stat = 0;            /* permanent status */
  397. X
  398. Xcode_int getcode();
  399. X
  400. XUsage() {
  401. X#ifdef DEBUG
  402. Xfprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  403. X}
  404. Xint debug = 0;
  405. X#else
  406. Xfprintf(stderr,"Usage: compress [-fvc] [-b maxbits] [file ...]\n");
  407. X}
  408. X#endif /* DEBUG */
  409. Xint nomagic = 0;    /* Use a 3-byte magic number header, unless old file */
  410. Xint zcat_flg = 0;    /* Write output on stdout, suppress messages */
  411. Xint precious = 1;    /* Don't unlink output file on interrupt */
  412. Xint quiet = 1;        /* don't tell me about compression */
  413. X
  414. X/*
  415. X * block compression parameters -- after all codes are used up,
  416. X * and compression rate changes, start over.
  417. X */
  418. Xint block_compress = BLOCK_MASK;
  419. Xint clear_flg = 0;
  420. Xlong int ratio = 0;
  421. X#define CHECK_GAP 10000    /* ratio check interval */
  422. Xcount_int checkpoint = CHECK_GAP;
  423. X/*
  424. X * the next two codes should not be changed lightly, as they must not
  425. X * lie within the contiguous general code space.
  426. X */ 
  427. X#define FIRST    257    /* first free entry */
  428. X#define    CLEAR    256    /* table clear output code */
  429. X
  430. Xint force = 0;
  431. Xchar ofname [100];
  432. X#ifdef DEBUG
  433. Xint verbose = 0;
  434. X#endif /* DEBUG */
  435. X#ifndef CMS
  436. Xint (*oldint)();
  437. X#else /*CMS*/
  438. Xvoid (*oldint)();
  439. X#endif /*CMS*/
  440. Xint bgnd_flag;
  441. X
  442. Xint do_decomp = 0;
  443. X
  444. X/*****************************************************************
  445. X * TAG( main )
  446. X *
  447. X * Algorithm from "A Technique for High Performance Data Compression",
  448. X * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  449. X *
  450. X * Usage: compress [-dfvc] [-b bits] [file ...]
  451. X * Inputs:
  452. X *    -d:        If given, decompression is done instead.
  453. X *
  454. X *      -c:         Write output on stdout, don't remove original.
  455. X *
  456. X *      -b:         Parameter limits the max number of bits/code.
  457. X *
  458. X *    -f:        Forces output file to be generated, even if one already
  459. X *            exists, and even if no space is saved by compressing.
  460. X *            If -f is not used, the user will be prompted if stdin is
  461. X *            a tty, otherwise, the output file will not be overwritten.
  462. X *
  463. X *      -v:        Write compression statistics
  464. X *
  465. X *     file ...:   Files to be compressed.  If none specified, stdin
  466. X *            is used.
  467. X * Outputs:
  468. X *    file.Z:        Compressed form of file with same mode, owner, and utimes
  469. X *     or stdout   (if stdin used as input)
  470. X *
  471. X * Assumptions:
  472. X *    When filenames are given, replaces with the compressed version
  473. X *    (.Z suffix) only if the file decreases in size.
  474. X * Algorithm:
  475. X *     Modified Lempel-Ziv method (LZW).  Basically finds common
  476. X * substrings and replaces them with a variable size code.  This is
  477. X * deterministic, and can be done on the fly.  Thus, the decompression
  478. X * procedure needs no input table, but tracks the way the table was built.
  479. X */
  480. X
  481. Xmain( argc, argv )
  482. Xregister int argc; char **argv;
  483. X{
  484. X    int overwrite = 0;    /* Do not overwrite unless given -f flag */
  485. X    char tempname[100];
  486. X    char **filelist, **fileptr;
  487. X    char *cp, *rindex(), *malloc();
  488. X    struct stat statbuf;
  489. X#ifdef CMS
  490. X    extern void onintr(), oops();
  491. X#else /*CMS*/
  492. X    extern onintr(), oops();
  493. X#endif /*CMS*/
  494. X
  495. X#ifdef CMS   /* allocate memory for lookup tables */
  496. X    htab = malloc( HSIZE*sizeof( code_int ) );
  497. X    codetab = malloc( HSIZE*sizeof( unsigned short ) );
  498. X    if ( htab==NULL || codetab==NULL ) {
  499. X        fputs( "Machine size too small.\n", stderr );
  500. X        exit(1);
  501. X    }
  502. X#endif /*CMS*/
  503. X
  504. X    /* This bg check only works for sh. */
  505. X    if ( (oldint = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  506. X    signal ( SIGINT, onintr );
  507. X#ifndef CMS    /* Does not exist in CMS */
  508. X    signal ( SIGSEGV, oops );
  509. X#endif /*CMS*/
  510. X    }
  511. X    bgnd_flag = oldint != SIG_DFL;
  512. X#ifdef notdef     /* This works for csh but we don't want it. */
  513. X    { int tgrp;
  514. X    if (bgnd_flag == 0 && ioctl(2, TIOCGPGRP, (char *)&tgrp) == 0 &&
  515. X      getpgrp(0) != tgrp)
  516. X    bgnd_flag = 1;
  517. X    }
  518. X#endif
  519. X    
  520. X#ifdef COMPATIBLE
  521. X    nomagic = 1;    /* Original didn't have a magic number */
  522. X#endif /* COMPATIBLE */
  523. X
  524. X    filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  525. X    *filelist = NULL;
  526. X
  527. X    if((cp = rindex(argv[0], '/')) != 0) {
  528. X    cp++;
  529. X    } else {
  530. X    cp = argv[0];
  531. X    }
  532. X    if(strcmp(cp, "uncompress") == 0) {
  533. X    do_decomp = 1;
  534. X    } else if(strcmp(cp, "zcat") == 0) {
  535. X    do_decomp = 1;
  536. X    zcat_flg = 1;
  537. X    }
  538. X
  539. X#ifdef BSD4_2
  540. X    /* 4.2BSD dependent - take it out if not */
  541. X    setlinebuf( stderr );
  542. X#endif /* BSD4_2 */
  543. X
  544. X    /* Argument Processing
  545. X     * All flags are optional.
  546. X     * -D => debug
  547. X     * -V => print Version; debug verbose
  548. X     * -d => do_decomp
  549. X     * -v => unquiet
  550. X     * -f => force overwrite of output file
  551. X     * -n => no header: useful to uncompress old files
  552. X     * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  553. X     *        given also.
  554. X     * -c => cat all output to stdout
  555. X     * -C => generate output compatible with compress 2.0.
  556. X     * if a string is left, must be an input filename.
  557. X     */
  558. X    for (argc--, argv++; argc > 0; argc--, argv++) {
  559. X    if (**argv == '-') {    /* A flag argument */
  560. X        while (*++(*argv)) {    /* Process all flags in this arg */
  561. X        switch (**argv) {
  562. X#ifdef DEBUG
  563. X            case 'D':
  564. X            debug = 1;
  565. X            break;
  566. X            case 'V':
  567. X            verbose = 1;
  568. X            version();
  569. X            break;
  570. X#else
  571. X            case 'V':
  572. X            version();
  573. X            break;
  574. X#endif /* DEBUG */
  575. X            case 'v':
  576. X            quiet = 0;
  577. X            break;
  578. X            case 'd':
  579. X            do_decomp = 1;
  580. X            break;
  581. X            case 'f':
  582. X            case 'F':
  583. X            overwrite = 1;
  584. X            force = 1;
  585. X            break;
  586. X            case 'n':
  587. X            nomagic = 1;
  588. X            break;
  589. X            case 'C':
  590. X            block_compress = 0;
  591. X            break;
  592. X            case 'b':
  593. X            if (!ARGVAL()) {
  594. X                fprintf(stderr, "Missing maxbits\n");
  595. X                Usage();
  596. X                exit(1);
  597. X            }
  598. X            maxbits = atoi(*argv);
  599. X            goto nextarg;
  600. X            case 'c':
  601. X            zcat_flg = 1;
  602. X            break;
  603. X            case 'q':
  604. X            quiet = 1;
  605. X            break;
  606. X            default:
  607. X            fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  608. X            Usage();
  609. X            exit(1);
  610. X        }
  611. X        }
  612. X    }
  613. X    else {        /* Input file name */
  614. X        *fileptr++ = *argv;    /* Build input file list */
  615. X        *fileptr = NULL;
  616. X        /* process nextarg; */
  617. X    }
  618. X    nextarg: continue;
  619. X    }
  620. X
  621. X    if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  622. X    if (maxbits > BITS) maxbits = BITS;
  623. X    maxmaxcode = 1 << maxbits;
  624. X
  625. X    if (*filelist != NULL) {
  626. X    for (fileptr = filelist; *fileptr; fileptr++) {
  627. X        exit_stat = 0;
  628. X        if (do_decomp) {            /* DECOMPRESSION */
  629. X        /* Check for .Z suffix */
  630. X        if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") != 0) {
  631. X            /* No .Z: tack one on */
  632. X            strcpy(tempname, *fileptr);
  633. X            strcat(tempname, ".Z");
  634. X            *fileptr = tempname;
  635. X        }
  636. X        /* Open input file */
  637. X        if ((freopen(*fileptr, "r", stdin)) == NULL) {
  638. X            perror(*fileptr);
  639. X            perm_stat = 1;
  640. X            continue;
  641. X        }
  642. X        /* Check the magic number */
  643. X        if (nomagic == 0) {
  644. X            if ((getchar() != (magic_header[0] & 0xFF))
  645. X             || (getchar() != (magic_header[1] & 0xFF))) {
  646. X            fprintf(stderr, "%s: not in compressed format\n",
  647. X                *fileptr);
  648. X            continue;
  649. X            }
  650. X            maxbits = getchar();    /* set -b from file */
  651. X            block_compress = maxbits & BLOCK_MASK;
  652. X            maxbits &= BIT_MASK;
  653. X            maxmaxcode = 1 << maxbits;
  654. X            if(maxbits > BITS) {
  655. X            fprintf(stderr,
  656. X            "%s: compressed with %d bits, can only handle %d bits\n",
  657. X            *fileptr, maxbits, BITS);
  658. X            continue;
  659. X            }
  660. X        }
  661. X        /* Generate output filename */
  662. X        strcpy(ofname, *fileptr);
  663. X        ofname[strlen(*fileptr) - 2] = '\0';  /* Strip off .Z */
  664. X        } else {                    /* COMPRESSION */
  665. X        if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") == 0) {
  666. X                fprintf(stderr, "%s: already has .Z suffix -- no change\n",
  667. X                *fileptr);
  668. X            continue;
  669. X        }
  670. X        /* Open input file */
  671. X        if ((freopen(*fileptr, "r", stdin)) == NULL) {
  672. X            perror(*fileptr);
  673. X            perm_stat = 1;
  674. X            continue;
  675. X        }
  676. X        stat ( *fileptr, &statbuf );
  677. X        fsize = (long) statbuf.st_size;
  678. X        /*
  679. X         * tune hash table size for small files -- ad hoc,
  680. X         * but the sizes match earlier #defines, which
  681. X         * serve as upper bounds on the number of output codes. 
  682. X         */
  683. X        hsize = HSIZE;
  684. X        if ( fsize < (1 << 12) )
  685. X            hsize = min ( 5003, HSIZE );
  686. X        else if ( fsize < (1 << 13) )
  687. X            hsize = min ( 9001, HSIZE );
  688. X        else if ( fsize < (1 << 14) )
  689. X            hsize = min ( 18013, HSIZE );
  690. X        else if ( fsize < (1 << 15) )
  691. X            hsize = min ( 35023, HSIZE );
  692. X        else if ( fsize < 47000 )
  693. X            hsize = min ( 50021, HSIZE );
  694. X
  695. X        /* Generate output filename */
  696. X        strcpy(ofname, *fileptr);
  697. X#ifndef BSD4_2        /* Short filenames */
  698. X        if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  699. X        else                    cp = ofname;
  700. X        if (strlen(cp) > 12) {
  701. X            fprintf(stderr,"%s: filename too long to tack on .Z\n",cp);
  702. X            continue;
  703. X        }
  704. X#endif  /* BSD4_2        Long filenames allowed */
  705. X        strcat(ofname, ".Z");
  706. X        }
  707. X        /* Check for overwrite of existing file */
  708. X        if (overwrite == 0 && zcat_flg == 0) {
  709. X        if (stat(ofname, &statbuf) == 0) {
  710. X            char response[2];
  711. X            response[0] = 'n';
  712. X            fprintf(stderr, "%s already exists;", ofname);
  713. X            if (bgnd_flag == 0 && isatty(2)) {
  714. X            fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  715. X            ofname);
  716. X            fflush(stderr);
  717. X            read(2, response, 2);
  718. X            while (response[1] != '\n') {
  719. X                if (read(2, response+1, 1) < 0) {    /* Ack! */
  720. X                perror("stderr"); break;
  721. X                }
  722. X            }
  723. X            }
  724. X            if (response[0] != 'y') {
  725. X            fprintf(stderr, "\tnot overwritten\n");
  726. X            continue;
  727. X            }
  728. X        }
  729. X        }
  730. X        if(zcat_flg == 0) {        /* Open output file */
  731. X        if (freopen(ofname, "w", stdout) == NULL) {
  732. X            perror(ofname);
  733. X            perm_stat = 1;
  734. X            continue;
  735. X        }
  736. X        precious = 0;
  737. X        if(!quiet)
  738. X            fprintf(stderr, "%s: ", *fileptr);
  739. X        }
  740. X
  741. X        /* Actually do the compression/decompression */
  742. X        if (do_decomp == 0)    compress();
  743. X#ifndef DEBUG
  744. X        else            decompress();
  745. X#else
  746. X        else if (debug == 0)    decompress();
  747. X        else            printcodes();
  748. X        if (verbose)        dump_tab();
  749. X#endif /* DEBUG */
  750. X        if(zcat_flg == 0) {
  751. X        copystat(*fileptr, ofname);    /* Copy stats */
  752. X        precious = 1;
  753. X        if((exit_stat == 1) || (!quiet))
  754. X            putc('\n', stderr);
  755. X        }
  756. X    }
  757. X    } else {        /* Standard input */
  758. X    if (do_decomp == 0) {
  759. X        compress();
  760. X#ifdef DEBUG
  761. X        if(verbose)        dump_tab();
  762. X#endif /* DEBUG */
  763. X        if(!quiet)
  764. X            putc('\n', stderr);
  765. X    } else {
  766. X        /* Check the magic number */
  767. X        if (nomagic == 0) {
  768. X        if ((getchar()!=(magic_header[0] & 0xFF))
  769. X         || (getchar()!=(magic_header[1] & 0xFF))) {
  770. X            fprintf(stderr, "stdin: not in compressed format\n");
  771. X            exit(1);
  772. X        }
  773. X        maxbits = getchar();    /* set -b from file */
  774. X        block_compress = maxbits & BLOCK_MASK;
  775. X        maxbits &= BIT_MASK;
  776. X        maxmaxcode = 1 << maxbits;
  777. X        fsize = 100000;        /* assume stdin large for USERMEM */
  778. X        if(maxbits > BITS) {
  779. X            fprintf(stderr,
  780. X            "stdin: compressed with %d bits, can only handle %d bits\n",
  781. X            maxbits, BITS);
  782. X            exit(1);
  783. X        }
  784. X        }
  785. X#ifndef DEBUG
  786. X        decompress();
  787. X#else
  788. X        if (debug == 0)    decompress();
  789. X        else        printcodes();
  790. X        if (verbose)    dump_tab();
  791. X#endif /* DEBUG */
  792. X    }
  793. X    }
  794. X    exit(perm_stat ? perm_stat : exit_stat);
  795. X}
  796. X
  797. Xstatic int offset;
  798. Xlong int in_count = 1;            /* length of input */
  799. Xlong int bytes_out;            /* length of compressed output */
  800. Xlong int out_count = 0;            /* # of codes output (for debugging) */
  801. X
  802. X/*
  803. X * compress stdin to stdout
  804. X *
  805. X * Algorithm:  use open addressing double hashing (no chaining) on the 
  806. X * prefix code / next character combination.  We do a variant of Knuth's
  807. X * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  808. X * secondary probe.  Here, the modular division first probe is gives way
  809. X * to a faster exclusive-or manipulation.  Also do block compression with
  810. X * an adaptive reset, whereby the code table is cleared when the compression
  811. X * ratio decreases, but after the table fills.  The variable-length output
  812. X * codes are re-sized at this point, and a special CLEAR code is generated
  813. X * for the decompressor.  Late addition:  construct the table according to
  814. X * file size for noticeable speed improvement on small files.  Please direct
  815. X * questions about this implementation to ames!jaw.
  816. X */
  817. X
  818. Xcompress() {
  819. X    register long fcode;
  820. X    register code_int i = 0;
  821. X    register int c;
  822. X    register code_int ent;
  823. X#ifdef XENIX_16
  824. X    register code_int disp;
  825. X#else    /* Normal machine */
  826. X    register int disp;
  827. X#endif
  828. X    register code_int hsize_reg;
  829. X    register int hshift;
  830. X
  831. X#ifndef COMPATIBLE
  832. X    if (nomagic == 0) {
  833. X    putchar(magic_header[0]); putchar(magic_header[1]);
  834. X    putchar((char)(maxbits | block_compress));
  835. X    if(ferror(stdout))
  836. X        writeerr();
  837. X    }
  838. X#endif /* COMPATIBLE */
  839. X
  840. X    offset = 0;
  841. X    bytes_out = 3;        /* includes 3-byte header mojo */
  842. X    out_count = 0;
  843. X    clear_flg = 0;
  844. X    ratio = 0;
  845. X    in_count = 1;
  846. X    checkpoint = CHECK_GAP;
  847. X    maxcode = MAXCODE(n_bits = INIT_BITS);
  848. X    free_ent = ((block_compress) ? FIRST : 256 );
  849. X
  850. X    ent = getchar ();
  851. X
  852. X    hshift = 0;
  853. X    for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  854. X        hshift++;
  855. X    hshift = 8 - hshift;        /* set hash code range bound */
  856. X
  857. X    hsize_reg = hsize;
  858. X    cl_hash( (count_int) hsize_reg);        /* clear hash table */
  859. X
  860. X#ifdef SIGNED_COMPARE_SLOW
  861. X    while ( (c = getchar()) != (unsigned) EOF ) {
  862. X#else
  863. X    while ( (c = getchar()) != EOF ) {
  864. X#endif
  865. X    in_count++;
  866. X    fcode = (long) (((long) c << maxbits) + ent);
  867. X     i = ((c << hshift) ^ ent);    /* xor hashing */
  868. X
  869. X    if ( htabof (i) == fcode ) {
  870. X        ent = codetabof (i);
  871. X        continue;
  872. X    } else if ( (long)htabof (i) < 0 )    /* empty slot */
  873. X        goto nomatch;
  874. X     disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
  875. X    if ( i == 0 )
  876. X        disp = 1;
  877. Xprobe:
  878. X    if ( (i -= disp) < 0 )
  879. X        i += hsize_reg;
  880. X
  881. X    if ( htabof (i) == fcode ) {
  882. X        ent = codetabof (i);
  883. X        continue;
  884. X    }
  885. X    if ( (long)htabof (i) > 0 ) 
  886. X        goto probe;
  887. Xnomatch:
  888. X    output ( (code_int) ent );
  889. X    out_count++;
  890. X     ent = c;
  891. X#ifdef SIGNED_COMPARE_SLOW
  892. X    if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  893. X#else
  894. X    if ( free_ent < maxmaxcode ) {
  895. X#endif
  896. X         codetabof (i) = free_ent++;    /* code -> hashtable */
  897. X        htabof (i) = fcode;
  898. X    }
  899. X    else if ( (count_int)in_count >= checkpoint && block_compress )
  900. X        cl_block ();
  901. X    }
  902. X    /*
  903. X     * Put out the final code.
  904. X     */
  905. X    output( (code_int)ent );
  906. X    out_count++;
  907. X    output( (code_int)-1 );
  908. X
  909. X    /*
  910. X     * Print out stats on stderr
  911. X     */
  912. X    if(zcat_flg == 0 && !quiet) {
  913. X#ifdef DEBUG
  914. X    fprintf( stderr,
  915. X        "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  916. X        in_count, out_count, bytes_out );
  917. X    prratio( stderr, in_count, bytes_out );
  918. X    fprintf( stderr, "\n");
  919. X    fprintf( stderr, "\tCompression as in compact: " );
  920. X    prratio( stderr, in_count-bytes_out, in_count );
  921. X    fprintf( stderr, "\n");
  922. X    fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  923. X        free_ent - 1, n_bits );
  924. X#else /* !DEBUG */
  925. X    fprintf( stderr, "Compression: " );
  926. X    prratio( stderr, in_count-bytes_out, in_count );
  927. X#endif /* DEBUG */
  928. X    }
  929. X    if(bytes_out > in_count)    /* exit(2) if no savings */
  930. X    exit_stat = 2;
  931. X    return;
  932. X}
  933. X
  934. X/*****************************************************************
  935. X * TAG( output )
  936. X *
  937. X * Output the given code.
  938. X * Inputs:
  939. X *     code:    A n_bits-bit integer.  If == -1, then EOF.  This assumes
  940. X *        that n_bits =< (long)wordsize - 1.
  941. X * Outputs:
  942. X *     Outputs code to the file.
  943. X * Assumptions:
  944. X *    Chars are 8 bits long.
  945. X * Algorithm:
  946. X *     Maintain a BITS character long buffer (so that 8 codes will
  947. X * fit in it exactly).  Use the VAX insv instruction to insert each
  948. X * code in turn.  When the buffer fills up empty it and start over.
  949. X */
  950. X
  951. Xstatic char buf[BITS];
  952. X
  953. X#ifndef vax
  954. Xchar_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  955. Xchar_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  956. X#endif /* vax */
  957. X
  958. Xoutput( code )
  959. Xcode_int  code;
  960. X{
  961. X#ifdef DEBUG
  962. X    static int col = 0;
  963. X#endif /* DEBUG */
  964. X
  965. X    /*
  966. X     * On the VAX, it is important to have the register declarations
  967. X     * in exactly the order given, or the asm will break.
  968. X     */
  969. X    register int r_off = offset, bits= n_bits;
  970. X    register char * bp = buf;
  971. X
  972. X#ifdef DEBUG
  973. X    if ( verbose )
  974. X        fprintf( stderr, "%5d%c", code,
  975. X            (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  976. X#endif /* DEBUG */
  977. X    if ( code >= 0 ) {
  978. X#ifdef vax
  979. X    /* VAX DEPENDENT!! Implementation on other machines is below.
  980. X     *
  981. X     * Translation: Insert BITS bits from the argument starting at
  982. X     * offset bits from the beginning of buf.
  983. X     */
  984. X    0;    /* Work around for pcc -O bug with asm and if stmt */
  985. X    asm( "insv    4(ap),r11,r10,(r9)" );
  986. X#else /* not a vax */
  987. X/* 
  988. X * byte/bit numbering on the VAX is simulated by the following code
  989. X */
  990. X    /*
  991. X     * Get to the first byte.
  992. X     */
  993. X    bp += (r_off >> 3);
  994. X    r_off &= 7;
  995. X    /*
  996. X     * Since code is always >= 8 bits, only need to mask the first
  997. X     * hunk on the left.
  998. X     */
  999. X    *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  1000. X    bp++;
  1001. X    bits -= (8 - r_off);
  1002. X    code >>= 8 - r_off;
  1003. X    /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1004. X    if ( bits >= 8 ) {
  1005. X        *bp++ = code;
  1006. X        code >>= 8;
  1007. X        bits -= 8;
  1008. X    }
  1009. X    /* Last bits. */
  1010. X    if(bits)
  1011. X        *bp = code;
  1012. X#endif /* vax */
  1013. X    offset += n_bits;
  1014. X    if ( offset == (n_bits << 3) ) {
  1015. X        bp = buf;
  1016. X        bits = n_bits;
  1017. X        bytes_out += bits;
  1018. X#ifndef CMS
  1019. X        do
  1020. X        putchar(*bp++);
  1021. X        while(--bits);
  1022. X#else /*CMS*/   /* avoid special handling of '15'x in CMS */
  1023. X            if ( fwrite( bp, sizeof(char), bits, stdout ) != bits )
  1024. X               writeerr();
  1025. X#endif /*CMS*/
  1026. X        offset = 0;
  1027. X    }
  1028. X
  1029. X    /*
  1030. X     * If the next entry is going to be too big for the code size,
  1031. X     * then increase it, if possible.
  1032. X     */
  1033. X    if ( free_ent > maxcode || (clear_flg > 0))
  1034. X    {
  1035. X        /*
  1036. X         * Write the whole buffer, because the input side won't
  1037. X         * discover the size increase until after it has read it.
  1038. X         */
  1039. X        if ( offset > 0 ) {
  1040. X        if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  1041. X            writeerr();
  1042. X        bytes_out += n_bits;
  1043. X        }
  1044. X        offset = 0;
  1045. X
  1046. X        if ( clear_flg ) {
  1047. X                maxcode = MAXCODE (n_bits = INIT_BITS);
  1048. X            clear_flg = 0;
  1049. X        }
  1050. X        else {
  1051. X            n_bits++;
  1052. X            if ( n_bits == maxbits )
  1053. X            maxcode = maxmaxcode;
  1054. X            else
  1055. X            maxcode = MAXCODE(n_bits);
  1056. X        }
  1057. X#ifdef DEBUG
  1058. X        if ( debug ) {
  1059. X        fprintf( stderr, "\nChange to %d bits\n", n_bits );
  1060. X        col = 0;
  1061. X        }
  1062. X#endif /* DEBUG */
  1063. X    }
  1064. X    } else {
  1065. X    /*
  1066. X     * At EOF, write the rest of the buffer.
  1067. X     */
  1068. X    if ( offset > 0 )
  1069. X        fwrite( buf, 1, (offset + 7) / 8, stdout );
  1070. X    bytes_out += (offset + 7) / 8;
  1071. X    offset = 0;
  1072. X    fflush( stdout );
  1073. X#ifdef DEBUG
  1074. X    if ( verbose )
  1075. X        fprintf( stderr, "\n" );
  1076. X#endif /* DEBUG */
  1077. X    if( ferror( stdout ) )
  1078. X        writeerr();
  1079. X    }
  1080. X}
  1081. X
  1082. X/*
  1083. X * Decompress stdin to stdout.  This routine adapts to the codes in the
  1084. X * file building the "string" table on-the-fly; requiring no table to
  1085. X * be stored in the compressed file.  The tables used herein are shared
  1086. X * with those of the compress() routine.  See the definitions above.
  1087. X */
  1088. X
  1089. Xdecompress() {
  1090. X    register char_type *stackp;
  1091. X    register int finchar;
  1092. X    register code_int code, oldcode, incode;
  1093. X
  1094. X    /*
  1095. X     * As above, initialize the first 256 entries in the table.
  1096. X     */
  1097. X    maxcode = MAXCODE(n_bits = INIT_BITS);
  1098. X    for ( code = 255; code >= 0; code-- ) {
  1099. X    tab_prefixof(code) = 0;
  1100. X    tab_suffixof(code) = (char_type)code;
  1101. X    }
  1102. X    free_ent = ((block_compress) ? FIRST : 256 );
  1103. X
  1104. X    finchar = oldcode = getcode();
  1105. X    if(oldcode == -1)    /* EOF already? */
  1106. X    return;            /* Get out of here */
  1107. X    putchar( (char)finchar );        /* first code must be 8 bits = char */
  1108. X    if(ferror(stdout))        /* Crash if can't write */
  1109. X    writeerr();
  1110. X    stackp = de_stack;
  1111. X
  1112. X    while ( (code = getcode()) > -1 ) {
  1113. X
  1114. X    if ( (code == CLEAR) && block_compress ) {
  1115. X        for ( code = 255; code >= 0; code-- )
  1116. X        tab_prefixof(code) = 0;
  1117. X        clear_flg = 1;
  1118. X        free_ent = FIRST - 1;
  1119. X        if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  1120. X        break;
  1121. X    }
  1122. X    incode = code;
  1123. X    /*
  1124. X     * Special case for KwKwK string.
  1125. X     */
  1126. X    if ( code >= free_ent ) {
  1127. X            *stackp++ = finchar;
  1128. X        code = oldcode;
  1129. X    }
  1130. X
  1131. X    /*
  1132. X     * Generate output characters in reverse order
  1133. X     */
  1134. X#ifdef SIGNED_COMPARE_SLOW
  1135. X    while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  1136. X#else
  1137. X    while ( code >= 256 ) {
  1138. X#endif
  1139. X        *stackp++ = tab_suffixof(code);
  1140. X        code = tab_prefixof(code);
  1141. X    }
  1142. X    *stackp++ = finchar = tab_suffixof(code);
  1143. X
  1144. X    /*
  1145. X     * And put them out in forward order
  1146. X     */
  1147. X    do
  1148. X        putchar ( *--stackp );
  1149. X    while ( stackp > de_stack );
  1150. X
  1151. X    /*
  1152. X     * Generate the new entry.
  1153. X     */
  1154. X    if ( (code=free_ent) < maxmaxcode ) {
  1155. X        tab_prefixof(code) = (unsigned short)oldcode;
  1156. X        tab_suffixof(code) = finchar;
  1157. X        free_ent = code+1;
  1158. X    } 
  1159. X    /*
  1160. X     * Remember previous code.
  1161. X     */
  1162. X    oldcode = incode;
  1163. X    }
  1164. X    fflush( stdout );
  1165. X    if(ferror(stdout))
  1166. X    writeerr();
  1167. X}
  1168. X
  1169. X/*****************************************************************
  1170. X * TAG( getcode )
  1171. X *
  1172. X * Read one code from the standard input.  If EOF, return -1.
  1173. X * Inputs:
  1174. X *     stdin
  1175. X * Outputs:
  1176. X *     code or -1 is returned.
  1177. X */
  1178. X
  1179. Xcode_int
  1180. Xgetcode() {
  1181. X    /*
  1182. X     * On the VAX, it is important to have the register declarations
  1183. X     * in exactly the order given, or the asm will break.
  1184. X     */
  1185. X    register code_int code;
  1186. X    static int offset = 0, size = 0;
  1187. X    static char_type buf[BITS];
  1188. X    register int r_off, bits;
  1189. X    register char_type *bp = buf;
  1190. X
  1191. X    if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1192. X    /*
  1193. X     * If the next entry will be too big for the current code
  1194. X     * size, then we must increase the size.  This implies reading
  1195. X     * a new buffer full, too.
  1196. X     */
  1197. X    if ( free_ent > maxcode ) {
  1198. X        n_bits++;
  1199. X        if ( n_bits == maxbits )
  1200. X        maxcode = maxmaxcode;    /* won't get any bigger now */
  1201. X        else
  1202. X        maxcode = MAXCODE(n_bits);
  1203. X    }
  1204. X    if ( clear_flg > 0) {
  1205. X            maxcode = MAXCODE (n_bits = INIT_BITS);
  1206. X        clear_flg = 0;
  1207. X    }
  1208. X    size = fread( buf, 1, n_bits, stdin );
  1209. X    if ( size <= 0 )
  1210. X        return -1;            /* end of file */
  1211. X    offset = 0;
  1212. X    /* Round size down to integral number of codes */
  1213. X    size = (size << 3) - (n_bits - 1);
  1214. X    }
  1215. X    r_off = offset;
  1216. X    bits = n_bits;
  1217. X#ifdef vax
  1218. X    asm( "extzv   r10,r9,(r8),r11" );
  1219. X#else /* not a vax */
  1220. X    /*
  1221. X     * Get to the first byte.
  1222. X     */
  1223. X    bp += (r_off >> 3);
  1224. X    r_off &= 7;
  1225. X    /* Get first part (low order bits) */
  1226. X#ifdef NO_UCHAR
  1227. X    code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1228. X#else
  1229. X    code = (*bp++ >> r_off);
  1230. X#endif /* NO_UCHAR */
  1231. X    bits -= (8 - r_off);
  1232. X    r_off = 8 - r_off;        /* now, offset into code word */
  1233. X    /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1234. X    if ( bits >= 8 ) {
  1235. X#ifdef NO_UCHAR
  1236. X        code |= (*bp++ & 0xff) << r_off;
  1237. X#else
  1238. X        code |= *bp++ << r_off;
  1239. X#endif /* NO_UCHAR */
  1240. X        r_off += 8;
  1241. X        bits -= 8;
  1242. X    }
  1243. X    /* high order bits. */
  1244. X    code |= (*bp & rmask[bits]) << r_off;
  1245. X#endif /* vax */
  1246. X    offset += n_bits;
  1247. X
  1248. X    return code;
  1249. X}
  1250. X
  1251. Xchar *
  1252. Xrindex(s, c)        /* For those who don't have it in libc.a */
  1253. Xregister char *s, c;
  1254. X{
  1255. X    char *p;
  1256. X    for (p = NULL; *s; s++)
  1257. X        if (*s == c)
  1258. X        p = s;
  1259. X    return(p);
  1260. X}
  1261. X
  1262. X#ifdef DEBUG
  1263. Xprintcodes()
  1264. X{
  1265. X    /*
  1266. X     * Just print out codes from input file.  For debugging.
  1267. X     */
  1268. X    code_int code;
  1269. X    int col = 0, bits;
  1270. X
  1271. X    bits = n_bits = INIT_BITS;
  1272. X    maxcode = MAXCODE(n_bits);
  1273. X    free_ent = ((block_compress) ? FIRST : 256 );
  1274. X    while ( ( code = getcode() ) >= 0 ) {
  1275. X    if ( (code == CLEAR) && block_compress ) {
  1276. X           free_ent = FIRST - 1;
  1277. X           clear_flg = 1;
  1278. X    }
  1279. X    else if ( free_ent < maxmaxcode )
  1280. X        free_ent++;
  1281. X    if ( bits != n_bits ) {
  1282. X        fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1283. X        bits = n_bits;
  1284. X        col = 0;
  1285. X    }
  1286. X    fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1287. X    }
  1288. X    putc( '\n', stderr );
  1289. X    exit( 0 );
  1290. X}
  1291. X
  1292. Xcode_int sorttab[1<<BITS];    /* sorted pointers into htab */
  1293. X
  1294. Xdump_tab()    /* dump string table */
  1295. X{
  1296. X    register int i, first;
  1297. X    register ent;
  1298. X#define STACK_SIZE    15000
  1299. X    int stack_top = STACK_SIZE;
  1300. X    register c;
  1301. X
  1302. X    if(do_decomp == 0) {    /* compressing */
  1303. X    register int flag = 1;
  1304. X
  1305. X    for(i=0; i<hsize; i++) {    /* build sort pointers */
  1306. X        if((long)htabof(i) >= 0) {
  1307. X            sorttab[codetabof(i)] = i;
  1308. X        }
  1309. X    }
  1310. X    first = block_compress ? FIRST : 256;
  1311. X    for(i = first; i < free_ent; i++) {
  1312. X        fprintf(stderr, "%5d: \"", i);
  1313. X        de_stack[--stack_top] = '\n';
  1314. X        de_stack[--stack_top] = '"';
  1315. X        stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1316. X                                     stack_top);
  1317. X        for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1318. X            ent > 256;
  1319. X            ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1320. X            stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1321. X                        stack_top);
  1322. X        }
  1323. X        stack_top = in_stack(ent, stack_top);
  1324. X        fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1325. X           stack_top = STACK_SIZE;
  1326. X    }
  1327. X   } else if(!debug) {    /* decompressing */
  1328. X
  1329. X       for ( i = 0; i < free_ent; i++ ) {
  1330. X       ent = i;
  1331. X       c = tab_suffixof(ent);
  1332. X       if ( isascii(c) && isprint(c) )
  1333. X           fprintf( stderr, "%5d: %5d/'%c'  \"",
  1334. X               ent, tab_prefixof(ent), c );
  1335. X       else
  1336. X           fprintf( stderr, "%5d: %5d/\\%03o \"",
  1337. X               ent, tab_prefixof(ent), c );
  1338. X       de_stack[--stack_top] = '\n';
  1339. X       de_stack[--stack_top] = '"';
  1340. X       for ( ; ent != NULL;
  1341. X           ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1342. X           stack_top = in_stack(tab_suffixof(ent), stack_top);
  1343. X       }
  1344. X       fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1345. X       stack_top = STACK_SIZE;
  1346. X       }
  1347. X    }
  1348. X}
  1349. X
  1350. Xint
  1351. Xin_stack(c, stack_top)
  1352. X    register c, stack_top;
  1353. X{
  1354. X    if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1355. X        de_stack[--stack_top] = c;
  1356. X    } else {
  1357. X        switch( c ) {
  1358. X        case '\n': de_stack[--stack_top] = 'n'; break;
  1359. X        case '\t': de_stack[--stack_top] = 't'; break;
  1360. X        case '\b': de_stack[--stack_top] = 'b'; break;
  1361. X        case '\f': de_stack[--stack_top] = 'f'; break;
  1362. X        case '\r': de_stack[--stack_top] = 'r'; break;
  1363. X        case '\\': de_stack[--stack_top] = '\\'; break;
  1364. X        default:
  1365. X         de_stack[--stack_top] = '0' + c % 8;
  1366. X         de_stack[--stack_top] = '0' + (c / 8) % 8;
  1367. X         de_stack[--stack_top] = '0' + c / 64;
  1368. X         break;
  1369. X        }
  1370. X        de_stack[--stack_top] = '\\';
  1371. X    }
  1372. X    return stack_top;
  1373. X}
  1374. X#endif /* DEBUG */
  1375. X
  1376. Xwriteerr()
  1377. X{
  1378. X    perror ( ofname );
  1379. X    unlink ( ofname );
  1380. X    exit ( 1 );
  1381. X}
  1382. X
  1383. Xcopystat(ifname, ofname)
  1384. Xchar *ifname, *ofname;
  1385. X{
  1386. X    struct stat statbuf;
  1387. X    int mode;
  1388. X    time_t timep[2];
  1389. X
  1390. X    fclose(stdout);
  1391. X#ifndef CMS           /* this whole section makes no sense on IBM VM/CMS */
  1392. X    if (stat(ifname, &statbuf)) {        /* Get stat on input file */
  1393. X    perror(ifname);
  1394. X    return;
  1395. X    }
  1396. X    if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1397. X    if(quiet)
  1398. X            fprintf(stderr, "%s: ", ifname);
  1399. X    fprintf(stderr, " -- not a regular file: unchanged");
  1400. X    exit_stat = 1;
  1401. X    perm_stat = 1;
  1402. X    } else if (statbuf.st_nlink > 1) {
  1403. X    if(quiet)
  1404. X            fprintf(stderr, "%s: ", ifname);
  1405. X    fprintf(stderr, " -- has %d other links: unchanged",
  1406. X        statbuf.st_nlink - 1);
  1407. X    exit_stat = 1;
  1408. X    perm_stat = 1;
  1409. X    } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1410. X    if(!quiet)
  1411. X        fprintf(stderr, " -- file unchanged");
  1412. X    } else {            /* ***** Successful Compression ***** */
  1413. X    exit_stat = 0;
  1414. X    mode = statbuf.st_mode & 07777;
  1415. X    if (chmod(ofname, mode))        /* Copy modes */
  1416. X        perror(ofname);
  1417. X    chown(ofname, statbuf.st_uid, statbuf.st_gid);    /* Copy ownership */
  1418. X    timep[0] = statbuf.st_atime;
  1419. X    timep[1] = statbuf.st_mtime;
  1420. X    utime(ofname, timep);    /* Update last accessed and modified times */
  1421. X    if (unlink(ifname))    /* Remove input file */
  1422. X        perror(ifname);
  1423. X    if(!quiet)
  1424. X        fprintf(stderr, " -- replaced with %s", ofname);
  1425. X    return;        /* Successful return */
  1426. X    }
  1427. X
  1428. X    /* Unsuccessful return -- one of the tests failed */
  1429. X    if (unlink(ofname))
  1430. X    perror(ofname);
  1431. X#endif /*CMS*/
  1432. X}
  1433. X
  1434. X#ifdef CMS
  1435. Xvoid onintr ( )
  1436. X#else /*CMS*/
  1437. Xonintr ( )
  1438. X#endif /*CMS*/
  1439. X{
  1440. X    if (!precious)
  1441. X    unlink ( ofname );
  1442. X    exit ( 1 );
  1443. X}
  1444. X
  1445. X#ifdef CMS
  1446. Xvoid oops ( )        /* wild pointer -- assume bad input */
  1447. X#else /*CMS*/
  1448. Xoops ( )    /* wild pointer -- assume bad input */
  1449. X#endif /*CMS*/
  1450. X{
  1451. X    if ( do_decomp ) 
  1452. X        fprintf ( stderr, "uncompress: corrupt input\n" );
  1453. X    unlink ( ofname );
  1454. X    exit ( 1 );
  1455. X}
  1456. X
  1457. Xcl_block ()        /* table clear for block compress */
  1458. X{
  1459. X    register long int rat;
  1460. X
  1461. X    checkpoint = in_count + CHECK_GAP;
  1462. X#ifdef DEBUG
  1463. X    if ( debug ) {
  1464. X            fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1465. X             prratio ( stderr, in_count, bytes_out );
  1466. X        fprintf ( stderr, "\n");
  1467. X    }
  1468. X#endif /* DEBUG */
  1469. X
  1470. X    if(in_count > 0x007fffff) {    /* shift will overflow */
  1471. X    rat = bytes_out >> 8;
  1472. X    if(rat == 0) {        /* Don't divide by zero */
  1473. X        rat = 0x7fffffff;
  1474. X    } else {
  1475. X        rat = in_count / rat;
  1476. X    }
  1477. X    } else {
  1478. X    rat = (in_count << 8) / bytes_out;    /* 8 fractional bits */
  1479. X    }
  1480. X    if ( rat > ratio ) {
  1481. X    ratio = rat;
  1482. X    } else {
  1483. X    ratio = 0;
  1484. X#ifdef DEBUG
  1485. X    if(verbose)
  1486. X        dump_tab();    /* dump string table */
  1487. X#endif
  1488. X     cl_hash ( (count_int) hsize );
  1489. X    free_ent = FIRST;
  1490. X    clear_flg = 1;
  1491. X    output ( (code_int) CLEAR );
  1492. X#ifdef DEBUG
  1493. X    if(debug)
  1494. X            fprintf ( stderr, "clear\n" );
  1495. X#endif /* DEBUG */
  1496. X    }
  1497. X}
  1498. X
  1499. Xcl_hash(hsize)        /* reset code table */
  1500. X    register count_int hsize;
  1501. X{
  1502. X#ifndef XENIX_16    /* Normal machine */
  1503. X    register count_int *htab_p = htab+hsize;
  1504. X#else
  1505. X    register j;
  1506. X    register long k = hsize;
  1507. X    register count_int *htab_p;
  1508. X#endif
  1509. X    register long i;
  1510. X    register long m1 = -1;
  1511. X
  1512. X#ifdef XENIX_16
  1513. X    for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1514. X    i = 8192;
  1515. X    if(k < 8192) {
  1516. X        i = k;
  1517. X    }
  1518. X    htab_p = &(htab[j][i]);
  1519. X    i -= 16;
  1520. X    if(i > 0) {
  1521. X#else
  1522. X    i = hsize - 16;
  1523. X#endif
  1524. X     do {                /* might use Sys V memset(3) here */
  1525. X        *(htab_p-16) = m1;
  1526. X        *(htab_p-15) = m1;
  1527. X        *(htab_p-14) = m1;
  1528. X        *(htab_p-13) = m1;
  1529. X        *(htab_p-12) = m1;
  1530. X        *(htab_p-11) = m1;
  1531. X        *(htab_p-10) = m1;
  1532. X        *(htab_p-9) = m1;
  1533. X        *(htab_p-8) = m1;
  1534. X        *(htab_p-7) = m1;
  1535. X        *(htab_p-6) = m1;
  1536. X        *(htab_p-5) = m1;
  1537. X        *(htab_p-4) = m1;
  1538. X        *(htab_p-3) = m1;
  1539. X        *(htab_p-2) = m1;
  1540. X        *(htab_p-1) = m1;
  1541. X        htab_p -= 16;
  1542. X    } while ((i -= 16) >= 0);
  1543. X#ifdef XENIX_16
  1544. X    }
  1545. X    }
  1546. X#endif
  1547. X        for ( i += 16; i > 0; i-- )
  1548. X        *--htab_p = m1;
  1549. X}
  1550. X
  1551. Xprratio(stream, num, den)
  1552. XFILE *stream;
  1553. Xlong int num, den;
  1554. X{
  1555. X    register int q;            /* Doesn't need to be long */
  1556. X
  1557. X    if(num > 214748L) {        /* 2147483647/10000 */
  1558. X        q = num / (den / 10000L);
  1559. X    } else {
  1560. X        q = 10000L * num / den;        /* Long calculations, though */
  1561. X    }
  1562. X    if (q < 0) {
  1563. X        putc('-', stream);
  1564. X        q = -q;
  1565. X    }
  1566. X    fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1567. X}
  1568. X
  1569. Xversion()
  1570. X{
  1571. X    fprintf(stderr, "%s, Berkeley 5.9 5/11/86\n", rcs_ident);
  1572. X    fprintf(stderr, "Options: ");
  1573. X#ifdef vax
  1574. X    fprintf(stderr, "vax, ");
  1575. X#endif
  1576. X#ifdef NO_UCHAR
  1577. X    fprintf(stderr, "NO_UCHAR, ");
  1578. X#endif
  1579. X#ifdef SIGNED_COMPARE_SLOW
  1580. X    fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1581. X#endif
  1582. X#ifdef XENIX_16
  1583. X    fprintf(stderr, "XENIX_16, ");
  1584. X#endif
  1585. X#ifdef COMPATIBLE
  1586. X    fprintf(stderr, "COMPATIBLE, ");
  1587. X#endif
  1588. X#ifdef DEBUG
  1589. X    fprintf(stderr, "DEBUG, ");
  1590. X#endif
  1591. X#ifdef BSD4_2
  1592. X    fprintf(stderr, "BSD4_2, ");
  1593. X#endif
  1594. X#ifdef CMS
  1595. X    fprintf(stderr, "CMS, ");
  1596. X#endif
  1597. X    fprintf(stderr, "BITS = %d\n", BITS);
  1598. X}
  1599. END_OF_FILE
  1600. if test 41795 -ne `wc -c <'compress.c'`; then
  1601.     echo shar: \"'compress.c'\" unpacked with wrong size!
  1602. fi
  1603. # end of 'compress.c'
  1604. fi
  1605. echo shar: End of shell archive.
  1606. exit 0
  1607.  
  1608.  
  1609.